package net.gagnat.android.trackit.service;

import java.util.ArrayList;
import java.util.List;

import net.gagnat.android.trackit.domain.LogTag;
import android.content.Context;

public class LogTagsRepository {

	private static LogTagsRepository logTagsRepository = null;

	private LogTagDbManager logTagDbManager;
	private List<LogTag> logTags = new ArrayList<LogTag>();

	private LogTagsRepository(Context context) {
		logTagDbManager = new LogTagDbManager(context);
		logTags.addAll(logTagDbManager.list());
	}

	/**
	 * Initializes the repository including instanciation of an arrayadapter.
	 * 
	 * @param context
	 *            The current context.
	 * @return
	 */
	public static LogTagsRepository initialize(Context context) {
		if (logTagsRepository == null) {
			logTagsRepository = new LogTagsRepository(context);
		}
		return getInstance();
	}

	public static boolean isInitialized() {
		return logTagsRepository != null;
	}

	public List<LogTag> getLogTags() {
		return logTags;
	}

	public static LogTagsRepository getInstance() {
		return logTagsRepository;
	}

	public void saveTag(LogTag newTag) {
		logTagDbManager.save(newTag);
		updateLogTagList();
	}

	public void updateTagList(List<String> tags) {
		for (String tag : tags) {
			String trimmedTag = tag.trim();
			if (!eksisterer(trimmedTag)) {
				LogTag newTag = new LogTag();
				newTag.setName(trimmedTag);
				saveTag(newTag);
			}
		}
		updateLogTagList();
	}

	private void updateLogTagList() {
		logTags.clear();
		logTags.addAll(logTagDbManager.list());
	}

	private boolean eksisterer(String tag) {
		for (LogTag logTag : logTags) {
			if (tag.equalsIgnoreCase(logTag.getName())) {
				return true;
			}
		}
		return false;
	}

}
